package com.party.admin.biz.mall;

import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.input.common.CommonQuery;
import com.party.common.paging.Page;
import com.party.core.exception.BusinessException;
import com.party.core.model.mall.MallShowGoods;
import com.party.core.model.mall.MallShowGoodsWithAuthor;
import com.party.core.model.mall.MallShowSubject;
import com.party.core.model.mall.MallShowSubjectTemplate;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.mall.IMallShowGoodsService;
import com.party.core.service.mall.IMallShowSubjectService;
import com.party.core.service.mall.IMallShowSubjectTemplateService;
import com.party.core.service.mall.biz.GoodsShowCountBizService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 展示商品服务接口
 * Created by wei.li
 *
 * @date 2017/8/26 0026
 * @time 9:30
 */

@Service
public class MallShowGoodsBizService {

    @Autowired
    private IMallShowGoodsService mallShowGoodsService;

    @Autowired
    private GoodsShowCountBizService goodsShowCountBizService;

    @Autowired
    private MallGoodsBizService mallGoodsBizService;

    @Autowired
    private DistributionBizService distributionBizService;

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;

    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;


    protected Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 商品列表数据
     *
     * @param mallShowGoodsWithAuthor 商品
     * @param page                    分页参数
     * @return 列表数据
     */
    public List<MallShowGoodsWithAuthor> list(MallShowGoodsWithAuthor mallShowGoodsWithAuthor, Page page) {

        if (null != mallShowGoodsWithAuthor.getTimeType() && !new Integer(0).equals(mallShowGoodsWithAuthor.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(mallShowGoodsWithAuthor.getTimeType());
            mallShowGoodsWithAuthor.setCreateStart(commonQuery.getCreateStart());
            mallShowGoodsWithAuthor.setCreateEnd(commonQuery.getCreateEnd());
        }
        return mallShowGoodsService.withAuthorListPage(mallShowGoodsWithAuthor, page);
    }

    /**
     * 保存展示商品
     *
     * @param mallShowGood 展示商品
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveBusiness(MallShowGoods mallShowGood) {
        String orgId = "";
        if (StringUtils.isNotEmpty(mallShowGood.getSubjectId())) {
            MallShowSubject mallShowSubject = mallShowSubjectService.get(mallShowGood.getSubjectId());
            orgId = mallShowSubject.getMemberId();
            if (StringUtils.isEmpty(orgId)) {
                throw new BusinessException("机构主题没有配置所属合作商");
            }
        }

        MemberGroup member = RealmUtils.getCurrentUser();
        //涉及表 MallShowGood
        if (StringUtils.isEmpty(mallShowGood.getId())) {
            //保存
            mallShowGood.setMemberId(member.getId());
            // 处理url, 有可能会没有http:
            String url = mallShowGood.getUrl();
            if (url.indexOf("http:") < 0 && url.indexOf("https:") < 0) {
                url = "http:" + url;
                mallShowGood.setUrl(url);
            }
            String mallShowGoodsId = mallShowGoodsService.insert(mallShowGood);

            // 统计商品数量
            try {
                goodsShowCountBizService.countGoodsNum(mallShowGoodsId, true);
            } catch (Exception e) {
                logger.error("保存商品时, 统计商品数量异常", e);
            }
            // 保存分销关系
            if (mallShowGood.getType() != null && StringUtils.isNotEmpty(mallShowGood.getTargetId()) && StringUtils.isNotEmpty(orgId)) {
                List<String> goodsIds = mallGoodsBizService.getGoodsIds(mallShowGood.getType(), mallShowGood.getTargetId());
                distributionBizService.saveShowGoodsDistributionBiz(orgId, goodsIds);
            }
        } else {
            MallShowGoods dbShowGoods = mallShowGoodsService.get(mallShowGood.getId());
            String oldTargetId = dbShowGoods.getTargetId();
            String newTargetId = mallShowGood.getTargetId();
            Integer newType = mallShowGood.getType();

            //更新
            mallShowGoodsService.update(mallShowGood);

            if (newType != null && StringUtils.isNotEmpty(newTargetId) && StringUtils.isNotEmpty(orgId)) {
                List<String> goodsIds = mallGoodsBizService.getGoodsIds(newType, newTargetId);
                if (StringUtils.isNotEmpty(oldTargetId) && !oldTargetId.equals(newTargetId)) {
                    distributionBizService.deleteShowGoodsDistributionBiz(mallShowGood.getMemberId(), goodsIds);
                }
                distributionBizService.saveShowGoodsDistributionBiz(orgId, goodsIds);
            }
        }
    }

    /**
     * 删除展示商品
     *
     * @param goodsId 商品编号
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteShowGoodsBiz(String goodsId) {
        try {
            List<MallShowGoods> mallShowGoods = mallShowGoodsService.findByTargetId(goodsId);
            for (MallShowGoods showGoods : mallShowGoods) {
                String subjectId = showGoods.getSubjectId();
                if (StringUtils.isNotEmpty(subjectId)) {
                    MallShowSubject mallShowSubject = mallShowSubjectService.get(subjectId);
                    if (mallShowSubject != null) {
                        Integer goodsNum = mallShowSubject.getGoodsNum();
                        goodsNum = goodsNum == null ? 0 : goodsNum - 1;
                        goodsNum = goodsNum <= 0 ? 0 : goodsNum;
                        mallShowSubject.setGoodsNum(goodsNum);
                        mallShowSubjectService.update(mallShowSubject);
                    }
                    MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(subjectId);
                    if (mallShowSubjectTemplate != null) {
                        Integer goodsNum = mallShowSubjectTemplate.getGoodsNum();
                        goodsNum = goodsNum == null ? 0 : goodsNum - 1;
                        goodsNum = goodsNum <= 0 ? 0 : goodsNum;
                        mallShowSubjectTemplate.setGoodsNum(goodsNum);
                        mallShowSubjectTemplateService.update(mallShowSubjectTemplate);
                    }
                }
                mallShowGoodsService.delete(showGoods.getId());
            }
            return true;
        } catch (Exception e) {
            logger.error("删除展示商品异常", e);
            return false;
        }
    }
}
